package cn.cjlmonster.hyouka_assistant.webView

import android.content.Context
import android.view.View
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory


/**
 * NativeWebViewFactory
 *
 * @author cjl
 * @date 2025/7/9 23:51
 */
class NativeWebViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {

    companion object {
        private const val CHANNEL = "cn.cjlmonster.hyouka/webview"

        @JvmStatic
        fun registerWith(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
            flutterPluginBinding.platformViewRegistry.registerViewFactory(
                CHANNEL,
                NativeWebViewFactory()
            )
        }
    }

    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
        val creationParams = args as? Map<*, *>
        val url = creationParams?.get("url") as? String ?: ""
        return NativeWebView(context, url)
    }
}

class NativeWebView(context: Context, url: String) : PlatformView {
    private val webView = WebViewPool.getInstance().acquireWebView(context).apply {
        loadUrl(url)
    }

    override fun getView(): View = webView
    override fun dispose() {}
}